﻿// --------------------------------------------------------------------------------------
// <copyright file="SqlCommandExtension.cs" company="NGroup">
// Copyright (c) NGroup. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------
// <history>
//     <change who="Bui Thanh Nam" date="2013.12.15">Create</change>
// </history>
// --------------------------------------------------------------------------------------

namespace NGroup.VTL.DAL.Extension
{
    using System.Data;
    using System.Data.SqlClient;

    internal static class SqlCommandExtension
    {
        public static SqlParameter AddInParameter(this SqlCommand command, string parameterName, object value)
        {
            parameterName = string.Format("@{0}", parameterName);            
            SqlParameter sqlParameter = command.Parameters.AddWithValue(parameterName, value);

            return sqlParameter;            
        }

        public static SqlParameter AddOutParameter(this SqlCommand command, string parameterName, object value)
        {
            parameterName = string.Format("@{0}", parameterName);
            SqlParameter sqlParameter = command.Parameters.AddWithValue(parameterName, value);

            sqlParameter.Direction = ParameterDirection.Output;

            return sqlParameter;
        }

        public static SqlParameter AddInOutParameter(this SqlCommand command, string parameterName, object value)
        {
            parameterName = string.Format("@{0}", parameterName);
            SqlParameter sqlParameter = command.Parameters.AddWithValue(parameterName, value);

            sqlParameter.Direction = ParameterDirection.InputOutput;

            return sqlParameter;
        }

        public static SqlParameter AddReturnParameter(this SqlCommand command, string parameterName, object value)
        {
            parameterName = string.Format("@{0}", parameterName);
            SqlParameter sqlParameter = command.Parameters.AddWithValue(parameterName, value);

            sqlParameter.Direction = ParameterDirection.ReturnValue;

            return sqlParameter;
        }

        public static DataSet ExecuteDataset(this SqlCommand command)
        {
            DataSet resultDS = new DataSet();

            using(SqlDataAdapter dataAdapter = new SqlDataAdapter())
            {
                dataAdapter.SelectCommand = command;
                dataAdapter.Fill(resultDS);
            }

            return resultDS;
        }

        public static object GetParameterValue(this SqlCommand command, string parameterName)
        {
            parameterName = string.Format("@{0}", parameterName);
            return command.Parameters[parameterName].Value;
        }
    }
}
